<?
require_once (__DIR__ . '/../../models/Accounts.php');
require_once (__DIR__ . '/../../models/Products.php');
RequireLogin();

if(isset($_POST['id'])) {
	$row = $_POST;
	$response = Products::Validate($row);
  
  if ($response === true) {
    if($row['id']==null) {
      $response = Products::Insert($row);
    }      
    else {
      $response = Products::Update($row);
    }
  }
  
  if ($response === true && !isset($_REQUEST['ajax'])) {
    header('Location: ' . $rootUrl . '/../W/Products/?inserted');
  }
}
else {
	if(!empty($_GET['id']))
		$row = Products::Get($_REQUEST['id']);
	else
		$row = Products::Blank();
}
	if(isset($_REQUEST['ajax']))
	{
		echo json_encode(array(
			'contents' => $row,
			'status' => $response === true ? 'success' : 'failed',
			'errors' => $response 
			));
		die();
	}
	
?>
					<? if(isset($response)): ?>
						<dl class="dl-horizontal error">
							<? foreach ($response as $key => $value) { ?>
								<dt><?=$key?></dt>
								<dd><?=$value?></dd>
							<? } ?>						
						</dl>
					<? endif; ?>
					<form class="form-horizontal" action="<?=$rootUrl?>/../W/Products/edit" method="post">
						<? function RenderInput($propertyName, $inputtype){ ?>
							<? global $row, $response; ?>
							<div class="control-group">
								<label class="control-label" for="<?=$propertyName?>"><?=$propertyName?>:</label>
								<div class="controls">
									<input 	type="<?=$inputtype?>" name="<?=$propertyName?>" id="<?=$propertyName?>" value="<?=$row[$propertyName]?>"
										   	class="<?=isset($response[$propertyName]) ? 'error' : '' ?>"
									/>
									<? if(isset($response[$propertyName])): ?>
										<span class="error"><?=$response[$propertyName]?></span>
									<? endif; ?>
								</div>
							</div>
						<? } ?>
						<?
							RenderInput('Name', 'text');
							RenderInput('Price', 'text');
							RenderInput('Description', 'text');
							RenderInput('Quantity', 'text');
						?>
	
						
						
						<div class="control-group">
							<div class="controls">
								<input type="hidden" name="id" value="<?php echo isset($row['id']) ? $row['id'] : '';?>" />
								<input type="submit" value="Save" class="btn btn-primary" />
							</div>
						</div>
				
					</form>
	
			<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.10.0/jquery.validate.min.js"></script>
			<script type="text/javascript">
				$(function(){
					
					$("form").validate(
						{
							rules: { created_at: { required: true} }
						}
					);
					
					$("input[type='datetime']").datepicker();
				});
			</script>
